import platform


def common():
    # This is a comment

    """
    This is a multiline comment
    """
    if 5 > 2:
        print("Five is greater than two!")

    # casting
    x = int(1)  # x will be 1
    y = int(2.8)  # y will be 2
    z = int("3")  # z will be 3

    x = input()
    print("Hello," + x)


def numbers():
    x = 1  # int
    y = 2.8  # float
    z = 1j  # complex
    print(type(x))
    print(type(y))
    print(type(z))


def strings():
    s = " Hello,World! "
    print(s[0])  # H
    print(s[6:11])  # World
    print(s.strip())
    print(s.lower())
    print(s.upper())
    print(s.replace("l", "L"))
    print(s.split(","))
    print(len(s))


def operators():
    print(5 / 2)  # 2.5
    print(5 // 2)  # 2
    print(5 ** 3)  # 125

    print("Python Logical Operators")
    print(1 and 1)
    print(1 or 0)
    print(not 1)

    print("Python Logical Operators")
    x = 1
    y = "1"
    print(x is y)
    print(x is not y)

    print("Python Membership  Operators")
    o = {x: 1, y: 2}
    print('x' in o)
    print('x' not in o)
    print('z' in o)


def lists():
    ls = ["apple", "banana", "cherry"]
    print(ls[0])
    ls[1] = "HuaWei"
    print(ls)
    for x in ls:
        print(x)
    if "apple" in ls:
        print("apple is contains in list")

    print("list len is " + str(len(ls)))
    ls.append("XiaoMi")
    ls.remove("cherry")
    print(ls.pop())
    print(ls)
    del ls[0]
    ls.clear()
    del ls


def tuples():
    tp = ("apple", "banana", "cherry")
    print(tp)
    tp2 = tuple(tp)
    print(tp2)
    print(tp2.count("apple"))
    print(tp2.index("cherry"))


def sets():
    thisset = {"apple", "banana", "cherry"}

    # Access Items
    for x in thisset:
        print(x)

    # add
    print("banana" in thisset)
    thisset.add("HuaWei")

    thisset.update(["orange", "mango", "grapes"])
    print(thisset)

    # len
    print(len(thisset))

    # remove element
    thisset.remove("apple")  # if the item to remove does not exits,remove() will raise an error
    thisset.discard("apple")  # If the item to remove does not exist, discard() will NOT raise an error.

    x = thisset.pop()
    print(x)

    # clear
    thisset.clear()
    print(thisset)

    del thisset

    # Constructor
    thisset = set(("apple", "banana", "cherry"))  # note the double round-brackets
    print(thisset)


def dictionary():
    dic = {
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }

    # Access Items
    print(dic["brand"])
    print(dic.get("brand"))

    # Loop Through a Dictionary
    for x in dic:
        print(x, ":", dic[x])

    # change
    dic["year"] = 2018
    print(dic)

    print(dic.values())

    # check if key exits
    print("model" in dic)

    # dic length
    print(len(dic))

    # adding items
    dic["ext"] = "ext_info"

    print(dic.pop("ext"))
    print(dic.popitem())
    del dic["model"]
    dic.clear()
    del dic


def lambdas():
    def myfunc(n):
        return lambda a: a * n

    double_func = myfunc(2)
    print(double_func(10))


def arrays():
    cars = ["Ford", "Volvo", "BMW"]
    for x in cars:
        print(x)
    cars.append("Honda")
    cars.pop(0)
    print(cars)
    cars.remove("Volvo")
    print(cars)


def class_test():
    p = Person("xiaoming", 18)
    print(p)
    p.myfunc()
    p.name = 'xiaoming2'
    p.myfunc()

    del p.name

    try:
        p.myfunc()  # raise an error
    except AttributeError:
        print("An exception occurred")

    del p


class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def myfunc(self):
        print("Hello my name is " + self.name)

    def __str__(self):
        return {"name": self.name, "age": self.age}.__str__()


class MyIterator:

    def __iter__(self):
        self.a = 1
        return self

    def __next__(self):
        if self.a > 20:
            raise StopIteration
        else:
            x = self.a
            self.a += 1
            return x


def iterators():
    # Return a iterator from a tuple, and print each value:
    mytuple = list(("apple", "banana", "cherry"))
    myit = iter(mytuple)

    print(next(myit))
    print(next(myit))
    print(next(myit))

    mystr = "banana"
    myit = iter(mystr)

    print(next(myit))
    print(next(myit))
    print(next(myit))
    print(next(myit))

    # Looping Through an Iterator
    for x in mytuple:
        print(x)

    myit = MyIterator()
    for x in myit:
        print(x)


def modules():
    print(dir(platform))
    print(platform.system())


import datetime


def dates():
    x = datetime.datetime.now()
    print(x)
    print(x.year)
    print(x.strftime("%A"))

    x = datetime.datetime(2020, 5, 17)
    print(x)
    print(x.strftime("%c"))


import json


def jsons():
    # some JSON:
    x = '{ "name":"John", "age":30, "city":"New York"}'

    # parse x:
    y = json.loads(x)

    # the result is a Python dictionary:
    print(y["age"])
    print(y)
    print(type(y))

    x = {
        "name": "John",
        "age": 30,
        "city": "New York"
    }
    # convert into JSON:
    y = json.dumps(x)
    print(y)
    print(type(y))


def try_except():
    try:
        print(x)
    except NameError:
        print("var not exits")
    except:
        print("An error occurred")
    else:
        print("Nothing went wrong")
    finally:
        print("function is finished")

    try:
        f = None
        f = open("test.txt")
        f.write("Lorum Ipsum")
    except:
        print("Something went wrong when writing to the file")
    finally:
        try:
            if f is not None:
                f.close()
        except:
            pass


import os


def file_handling():
    # open mode r(read) a(append) w(write) x(create)
    # t open in text mode , b open in binary mode

    # write files
    try:
        f = open("test.txt", "at")
        f.writelines(["Hello World\n"])
    finally:
        try:
            f.close()
        except:
            pass

    # Read files
    f = open("test.txt", "rt")
    print(f.read())
    f.close()

    # Delete a file
    os.remove("test.txt")

    # check if file exist
    exitsts = os.path.exists("test.txt")
    print(exitsts)

    # delete empty  folder
    os.rmdir("C:\\Users\\Dell\\Desktop\\dist(1)")


if __name__ == '__main__':
    file_handling()
